
package org.apache.ocean;

import org.apache.commons.lang.*;
import org.apache.ocean.server.*;
import org.jdom.*;
import java.math.*;

/**
 *
 * @author jasonr
 */
public class TransactionID implements Comparable, Cloneable {
  public BigInteger value;
  
  public Object clone() {
  	return new TransactionID(value.toString());
  }
  
  public TransactionID(BigInteger value) {
    this.value = value;
  }
  
  public TransactionID(CLong value) {
    this.value = new BigInteger(value.toString());
  }
  
  public TransactionID(long l) {
    value = new BigInteger(Long.toString(l));
  }
  
  public TransactionID(Element element) {
    value = new BigInteger(element.getText());
  }
  
  public static TransactionID fromIndexEncoded(String indexEncoded, IndexSchema indexSchema) {
    SchemaField schemaField = indexSchema.getField(ClusterConstants.TRANSACTION_ID_FIELD);
    String string = schemaField.getFieldType().indexedToReadable(indexEncoded);
    return new TransactionID(string);
  }
  
  public String toIndexEncoded(IndexSchema indexSchema) {
    SchemaField schemaField = indexSchema.getField(ClusterConstants.TRANSACTION_ID_FIELD);
    String internal = schemaField.getFieldType().toInternal(value.toString());
    return internal;
  }
  
  public static TransactionID parse(String string) {
    if (StringUtils.isBlank(string)) {
      return null;
    }
    return new TransactionID(string);
  }
  
  public int hashCode() {
    return value.hashCode();
  }
  
  public boolean equals(Object object) {
    TransactionID transactionID = (TransactionID)object;
    return value.equals(transactionID.value);
  }
  
  public int compareTo(Object object) {
    TransactionID other = (TransactionID)object;
    if (other.value == null && this.value == null) return 0;
    return this.value.compareTo(other.value);
  }
  
  public TransactionID increment() {
    value = value.add(new BigInteger("1"));
    return this;
  }
  
  public void decrement() {
    value = value.subtract(new BigInteger("1"));
  }
  
  public long getLong() {
    return value.longValue();
  }
  
  public Element toElement() {
    Element element = new Element("transactionid");
    element.setText(toString());
    return element;
  }
  
  public TransactionID(String string) {
    if (StringUtils.isBlank(string)) {
      throw new IllegalArgumentException("string blank: "+string);
    }
    value = new BigInteger(string);
  }
  
  public String toString() {
    return value.toString();
  }
}
